let express = require("express");
let fs = require("fs");
let path = require("path");

let router = express();


// 注册
router.get("/doregister",(request,response,next) => {
    let {username,password} = request.query;

    let read = fs.readFileSync("./mingdan.json");

    let readAdd = JSON.parse(read);

    let num = readAdd.findIndex((a) => {
        return a.username == username;
    });
    if(num == -1){
        readAdd.push({username,password});
        fs.writeFileSync("./mingdan.json",JSON.stringify(readAdd));
        response.send("注册成功");
    }else{
        // response.send("该账号已被注册");
        next("该账号已被注册");
    }



})


// 登录
router.get("/dologin",(request,response,next) => {
    let {username,password} = request.query;
    let read = fs.readFileSync("./mingdan.json");
    let readAdd = JSON.parse(read);
    let num = readAdd.findIndex((a) => {
        return a.username == username && a.password == password;
    });
    if(num != -1){
        response.send("登录成功");
    }else{
        let num = readAdd.findIndex((a) => {
            return a.username == username;
        });
        if(num == -1){
            // response.send("账号不正确");
            next("账号不正确");
        }else{
            // response.send("密码不正确");
            next("密码不正确");
        }
    }

});

module.exports = router;